package cn.biplam.front;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.biplam.common.client.AjxExchange;
import cn.biplam.common.client.Log;
import cn.biplam.common.client.Log.Log_Level;
import cn.biplam.common.tools.DEBUG;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.KvMap;
import cn.biplam.common.wrapper.UserInfo;

public class AjxServer extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public AjxServer() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
		this.doPost(request, response); 
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			try{
				/**交换码/功能代码,用于指示该请求对应的功能组件*/
				String action=request.getParameter(".act");
				/**无交换码,不执行*/
				if(action == null ){
					throw new ErrorMessage("Missing parameter:ActionID!");
				}else if(request.getParameter(".tid")==null){
					DEBUG.println("CID==("+request.getParameter(".cid")+","+"null".equals(request.getParameter(".cid"))+")");
					throw new ErrorMessage("Missing parameter:TargetID!");
				}

				/**从session中取用户信息*/
				UserInfo mUser;
				try {
					mUser = (UserInfo)request.getSession().getAttribute("userInfo");
				} catch (ClassCastException e) {
					throw new ErrorMessage("Can not get UserInfo from Session!");
				}
				/**无用户session,抛出异常*/
				if(mUser == null ){
					throw new ErrorMessage("No logined!");
				}

				/***********************************************************************/
				/**返回内容容器,传递给具体处理组件写入*/
				/**页面提交数据容器*/
				KvMap<String, String> params=new KvMap<String, String>();
				Iterator<?> ite=request.getParameterMap().keySet().iterator();
				String key=null;
				while(ite.hasNext()){
					key=ite.next().toString();
					params.put(key, request.getParameter(key));
				}
				params.removeByKey(".act");
				params.removeByKey(".uid");//userid从页面Session获取，暂时不使用ajx传递来的uid

				/**取主页地址*/
				String sHomeUrl=request.getContextPath();

				/**将内容容器和参数转发给Ajx交换器*/
				String sb=null;
				sb = AjxExchange.get(action,params,sHomeUrl,mUser);
				if(sb==null){
					throw new ErrorMessage("Ajx Exchange result is null:"+action+".");
				}
				response.getOutputStream().write(sb.toString().getBytes("UTF-8"));
				response.getOutputStream().flush();
			}catch (ErrorMessage e) {
				throw e;
			}catch (Exception e) {
				throw new ErrorMessage(e);
			}
		}catch (ErrorMessage e) {
			//返回异常页面提示
			StringBuilder sb = new StringBuilder();
			sb.append("<ajxtalertfcajxt><ajxb");
			sb.append(getAlert(e));
			sb.append("ajxb>");
			response.getOutputStream().write(sb.toString().getBytes("UTF-8"));
			response.getOutputStream().flush();
			Log.write(e,Log_Level.Error);
		}
	}

	public static String getAlert(ErrorMessage e){
		StringBuilder sb = new StringBuilder("Alert('服务器端异常',\"");
		if(e.getMessage()!=null){
			sb.append(e.getMessage().replace("\n", "<BR>").replace(";", "<BR>").replace('\"', '\''));
		}else{
			sb.append("Null");
		}
		sb.append("<BR>\tat ");
		sb.append(e.getAddress());
		sb.append("\");");
		return sb.toString();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
